package com.iyoudoock.citymine.activity.user;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.iyoudoock.citymine.BaseActivity;
import com.iyoudoock.citymine.R;
import com.iyoudoock.citymine.activity.DistrictListActivity;
import com.iyoudoock.citymine.activity.MapActivity;
import com.iyoudoock.citymine.constants.HttpUtils;
import com.iyoudoock.citymine.constants.Key;
import com.iyoudoock.citymine.constants.Value;
import com.iyoudoock.citymine.utils.ImageUtils;
import com.iyoudoock.citymine.widget.RegionPop;
import com.kvin.toolkit.constants.Interaction;
import com.kvin.toolkit.utils.FileUtils;
import com.kvin.toolkit.utils.JumpUtils;
import com.kvin.toolkit.utils.ListUtils;
import com.kvin.toolkit.utils.LogUtils;
import com.kvin.toolkit.utils.ToastUtils;
import com.kvin.toolkit.utils.http.JsonUtils;
import com.kvin.toolkit.utils.region.ProvinceBean;
import com.kvin.toolkit.utils.system.AnimUtils;
import com.kvin.toolkit.utils.system.PermissionUtils;
import com.nereo.imageselector.MultiImageSelector;
import com.nereo.imageselector.MultiImageSelectorActivity;


import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class RegisterRecyclerActivity extends BaseActivity {
    public static final String TAG = RegisterRecyclerActivity.class.getSimpleName();
    @BindView(R.id.nick_name_et)
    EditText nickNameEt;
    @BindView(R.id.sex_rg)
    RadioGroup sexRg;
    @BindView(R.id.age_et)
    EditText ageEt;
    @BindView(R.id.address_tv)
    TextView addressTv;
    @BindView(R.id.detail_address_tv)
    TextView detailAddressTv;
    @BindView(R.id.tips_tv)
    TextView tipsTv;
    @BindView(R.id.phone_et)
    EditText phoneEt;
    @BindView(R.id.person_front_iv)
    ImageView personFrontIv;
    @BindView(R.id.card_front_iv)
    ImageView cardFrontIv;
    @BindView(R.id.card_back_iv)
    ImageView cardBackIv;
    @BindView(R.id.car_iv)
    ImageView carIv;
    @BindView(R.id.psw_et)
    EditText pswEt;
    @BindView(R.id.confirm_psw_et)
    EditText confirmPswEt;
    @BindView(R.id.store_btn)
    Button registerBtn;
    @BindView(R.id.contact_service_tv)
    TextView contactServiceTv;

    private RegionPop mPop;
    private String personFrontImage;
    private String cardFrontImage;
    private String cardBackImage;
    private String carImage;
    private String districtId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_recycler);
        ButterKnife.bind(this);
    }

    @Override
    public void initNav() {
        setTitle("填写信息");
    }

    @Override
    public void init() {
        initPop();
        initRegion();
        initDialog();
        mJsonUtils = JsonUtils.getInstance();

        String phone = getIntent().getStringExtra(Key.User.TELEPHONE);
        if (!TextUtils.isEmpty(phone))
            this.phoneEt.setText(phone);
        this.contactServiceTv.setOnClickListener(this);
        this.addressTv.setOnClickListener(this);
        this.personFrontIv.setOnClickListener(this);
        this.cardFrontIv.setOnClickListener(this);
        this.cardBackIv.setOnClickListener(this);
        this.carIv.setOnClickListener(this);
        this.registerBtn.setOnClickListener(this);
        this.detailAddressTv.setOnClickListener(this);

        sexRg.setOnCheckedChangeListener(mOnCheckedChangeListener);
    }


    @Override
    public int checkCallingOrSelfPermission(String permission) {
        return super.checkCallingOrSelfPermission(permission);
    }

    /**
     * init dialog
     */
    @Override
    public void initDialog() {

    }

    /**
     * init address pop
     */
    private void initPop() {
        mPop = RegionPop.getInstance(this);
        mPop.setOnCancelClickListener(this);
        mPop.setOnSubmitClickListener(this);
    }


    private RadioGroup.OnCheckedChangeListener mOnCheckedChangeListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            RadioButton rb = (RadioButton) findViewById(checkedId);
            LogUtils.d("------" + rb.getText());
        }
    };


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.contact_service_tv:
                break;
            case R.id.detail_address_tv:
                selectDetailAddress();
                break;
            case R.id.address_tv:
                mPop.show(addressTv, Gravity.BOTTOM);
                break;
            case R.id.person_front_iv:
                selectImage(Value.Request.REQUEST_PERSON_FRONT);
                break;
            case R.id.card_front_iv:
                selectImage(Value.Request.REQUEST_CARD_FRONT);
                break;
            case R.id.card_back_iv:
                selectImage(Value.Request.REQUEST_CARD_BACK);
                break;
            case R.id.car_iv:
                selectImage(Value.Request.REQUEST_CAR_FRONT);
                break;
            case R.id.store_btn:
                register();
                break;
            case R.id.cancel_tv:
                mPop.dismiss();
                break;
            case R.id.confirm_tv:
                addressTv.setText(mPop.getAddress("-"));
                mPop.dismiss();
                break;
        }
    }

    /**
     * select detail address
     */
    private void selectDetailAddress() {
        String address = addressTv.getText().toString();
        if (TextUtils.isEmpty(address)) {
            ToastUtils.simpleToast(this, "请先选择地址");
            return;
        }
        mIntent = new Intent(this, DistrictListActivity.class);
        mIntent.putExtra(Key.User.ADDRESS, address);
        mIntent.putExtra(Key.Tag.FROM, Value.Act.REGISTER);
        JumpUtils.jumpWithResult(this, null, mIntent, Value.Request.REQUEST_DISTRICT_ID, AnimUtils.AnimStyle.RIGHT_IN_FADE_OUT);
    }

    /**
     * select  image
     *
     * @param requestCode
     */
    private void selectImage(int requestCode) {
        if (!PermissionUtils.isPermitted(getActivity(), Interaction.Permissions.Camera)) {
            PermissionUtils.requestPermission(getActivity(), Interaction.Permissions.Camera, requestCode);
        } else {
            launchImageSelector(requestCode);
        }
    }

    /**
     * launch image selector
     *
     * @param requestCode
     */
    private void launchImageSelector(int requestCode) {
        MultiImageSelector.create()
                .showCamera(true)
                .single()
                .start(getActivity(), requestCode);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults == null || grantResults.length < 1) return;

        if (requestCode == Value.Request.REQUEST_PERSON_FRONT) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                launchImageSelector(Value.Request.REQUEST_PERSON_FRONT);
            }
        } else if (requestCode == Value.Request.REQUEST_CARD_FRONT) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                launchImageSelector(Value.Request.REQUEST_CARD_FRONT);
            }
        } else if (requestCode == Value.Request.REQUEST_CARD_BACK) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                launchImageSelector(Value.Request.REQUEST_CARD_BACK);
            }
        } else if (requestCode == Value.Request.REQUEST_CAR_FRONT) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                launchImageSelector(Value.Request.REQUEST_CAR_FRONT);
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) return;
        List<String> results = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
        switch (requestCode) {
            case Value.Request.REQUEST_PERSON_FRONT:
                if (ListUtils.isEmpty(results)) return;
                ImageUtils.display(getActivity(), FileUtils.IMAGE_PREFIX_S + results.get(0), personFrontIv);
                personFrontImage = ImageUtils.convertBitmapToString(results.get(0));
                break;
            case Value.Request.REQUEST_CARD_FRONT:
                if (ListUtils.isEmpty(results)) return;
                ImageUtils.display(getActivity(), FileUtils.IMAGE_PREFIX_S + results.get(0), cardFrontIv);
                cardFrontImage = ImageUtils.convertBitmapToString(results.get(0));
                break;
            case Value.Request.REQUEST_CARD_BACK:
                if (ListUtils.isEmpty(results)) return;
                ImageUtils.display(getActivity(), FileUtils.IMAGE_PREFIX_S + results.get(0), cardBackIv);
                cardBackImage = ImageUtils.convertBitmapToString(results.get(0));
                break;
            case Value.Request.REQUEST_CAR_FRONT:
                if (ListUtils.isEmpty(results)) return;
                ImageUtils.display(getActivity(), FileUtils.IMAGE_PREFIX_S + results.get(0), carIv);
                carImage = ImageUtils.convertBitmapToString(results.get(0));
                break;
            case Value.Request.REQUEST_DISTRICT_ID:
                detailAddressTv.setText(data.getStringExtra(Key.User.DISTRICT));
                districtId = String.valueOf(data.getIntExtra(Key.User.DISTRICT_ID, -1));
                break;
        }
    }

    /**
     * register
     */
    private void register() {
        String phoneNo = phoneEt.getText().toString();
        String userName = nickNameEt.getText().toString();
        String sex = ((RadioButton) findViewById(sexRg.getCheckedRadioButtonId())).getText().toString();
        String age = ageEt.getText().toString();
        String address = addressTv.getText().toString();
        String community = detailAddressTv.getText().toString();
//        personFrontImage = "";
//        cardFrontImage = "";
//        cardBackImage = "";
//        carImage = "";
        String psw = pswEt.getText().toString();
        String roleType = getIntent().getStringExtra(Key.User.ROLE_TYPE);
        //check whether key words are null
        if (TextUtils.isEmpty(phoneNo)) {
            ToastUtils.simpleToast(this, "电话不能为空");
            return;
        }
        if (TextUtils.isEmpty(community) || districtId.equals("-1")) {
            ToastUtils.simpleToast(this, "小区id不能为空，请选择服务小区");
            return;
        }
        params = HttpUtils.getRegisterParams(phoneNo, roleType, userName, sex, age, address + community,
                personFrontImage, cardFrontImage, cardBackImage, carImage, psw, districtId);
        mJsonUtils.post(HttpUtils.REGISTER_URL, params, this, Value.Flag.REGISTER);

    }

    @SuppressWarnings("unchecked")
    @Override
    public void onHandleMessage(Message msg) {
        super.onHandleMessage(msg);
        if (msg.obj == null) return;
        mPop.setRegion((List<ProvinceBean>) msg.obj);

    }

    @Override
    public void onSuccess(JSONObject response, String flag) {
        super.onSuccess(response, flag);
        if (response == null) return;
        try {
            int state = response.getInt(Key.Tag.STATE);
            if (flag.equals(Value.Flag.REGISTER)) {
                if (state == Value.Response.SUCCESS) {
                    JumpUtils.simpleJump(getActivity(), LoginActivity.class, true);
                    ToastUtils.simpleToast(getActivity(), R.string.tip_register_bin_success);
                } else {
                    String msg = response.getString(Key.Tag.MSG);
                    ToastUtils.simpleToast(getActivity(), msg);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(IOException e, String flag) {
        super.onFailure(e, flag);
    }
}
